CLOUD_MIN_FONT = 8; // px
CLOUD_MAX_FONT = 20; // px
CLOUD_JSON_NUM = 50; // Number of items to retrieve at a time, max 50
CLOUD_JSON_MAX = 150; // Maximum number of items to retrieve, increments of CLOUD_JSON_NUM, 0=all
CLOUD_JSON_URL = 'http://boomtownstories.com/api/read/json';
CLOUD_POST_URL = 'http://boomtownstories.com/post';
CLOUD_TAG_URL = 'http://boomtownstories.com/tagged';

var cloud_has_links = true;
var cloud_tags = new Array();
var cloud_count = new Array();
var cloud_posts = new Array();
var cloud_text = new Array();
var cloud_total = 0;
var cloud_done = 0;
var cloud_html = '';
var cloud_max = 0;
var cloud_request;

function buildCloud() {
  cloud_request = new JSONscriptRequest(CLOUD_JSON_URL + '?callback=tumblrCallback&start='+cloud_done+'&num='+CLOUD_JSON_MAX);
  cloud_request.buildScriptTag();
  cloud_request.addScriptTag();
}

function tumblrCallback(obj) {
  cloud_total = obj['posts-total'];
  var curr = obj['posts'].length;
  
  for(var i=0; i<curr; ++i) {
    var tid = parseInt(obj['posts'][i]['id']);
    var turl = obj['posts'][i]['url'];
    var ttext = obj['posts'][i]['regular-title'];

    if(typeof(obj['posts'][i]['tags']) != 'undefined') {
      for(var j=0; j<obj['posts'][i]['tags'].length;++j) {
        var tname = obj['posts'][i]['tags'][j];
        var safetag = tname.replace(/'/, '');

        if(typeof(cloud_count[safetag]) == 'undefined') {
          cloud_count[safetag] = 0;
          cloud_tags.push(tname);
          cloud_posts[safetag] = new Array();
        }

        cloud_posts[safetag].push( new Array(turl, ttext) );
        cloud_count[safetag]++;
        if(cloud_count[safetag] > cloud_max) 
          cloud_max = cloud_count[safetag];
      }
    }
  }
  cloud_done += curr;

  if((cloud_done < cloud_total) && (CLOUD_JSON_MAX == 0 || cloud_done < CLOUD_JSON_MAX)) {
    cloud_request.removeScriptTag();
    buildCloud();
  } else {
    renderCloud();
  }
}

function renderCloud() {
  var sorted = cloud_tags.sort();
  for(var i=0; i<sorted.length; ++i) {
    var safetag = cloud_tags[i].replace(/'/, '');
    var items = cloud_count[safetag];
    var ratio = items/cloud_max;
    var fclass = 'normal';
    if(ratio < 0.2) fclass = 'smaller'
      else if(ratio < 0.4) fclass = 'small'
      else if(ratio < 0.6) fclass = 'normal'
      else if(ratio < 0.8) fclass = 'big'
      else fclass = 'bigger';
    fclass = 'cloud-' + fclass;

    if(cloud_has_links)
      cloud_html += '<li class="' + fclass + '"><a href="'+CLOUD_TAG_URL+'/'+safetag+'">'+cloud_tags[i]+'</a></li> ';
    else
      cloud_html += '<li class="' + fclass + '">'+cloud_tags[i]+'</a></li> ';
  }
  var tc = document.getElementById('tagcloud');
  tc.innerHTML = cloud_html;

  cloud_request.removeScriptTag();
}